<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form isheader" v-if="headerShow">
                <div>
                    <a-form size="small" :model="pageData" layout="inline">
                        <a-form-item label="织单类型">
                            <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading" :allowClear="true"
                            @search="handleSearch" v-model="pageData.dropDownData" :filter-option="false" allow-search
                            @focus="focusSel">
                            <a-option v-for="item in pageData.clothList" :value="item.yarnCode">{{
                                item.yarnCode
                            }}</a-option>
                        </a-select> -->
                            <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                                v-model="pageData.dropDownData" @press-enter="huiche" />
                        </a-form-item>
                        <a-form-item :style="{ width: '345px' }" label-col-flex="100px" label="是否本集团">
                            <a-select popup-container="html"  allow-clear :class="{ bacClass: true }" v-model="pageData.outsideState">
                                <a-option :value="0">本集团</a-option>
                                <a-option :value="1">外加工</a-option>
                            </a-select>
                        </a-form-item>
                    </a-form>
                </div>
                <div>
                    <Toolbar :items="[
                        `${permissionStore.hasPermisson('zdlxwh.cx') ? '查询' : ''}`,
                        `${permissionStore.hasPermisson('zdlxwh.xz') ? '新增' : ''}`,
                        `${permissionStore.hasPermisson('zdlxwh.sc') ? '删除' : ''}`,]" @add="addHandler"
                        @import="importHandler" @del="deleteHandler" @select="selectHandler" @export="exports"
                        @excel="downloadHandler">
                    </Toolbar>
                </div>
            </div>

            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                    <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
            <!-- <div class="my-tool-bar">
                <Toolbar :items="pageData.btnList" @add="addHandler" @import="importHandler" @del="deleteHandler"
                    @select="selectHandler" @export="exports" @excel="downloadHandler">
                </Toolbar>
            </div> -->
        </template>
        <template #pageTabel>

            <!-- <a-table size="mini" style="height:100%" :scrollbar="true" sticky-header @change="handleChange"  :draggable="{type:'handle',width:20,fixed:true}"
                             @page-change="pagination.change" stripe :bordered="true" :columns="tableColumns"
                        :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
                        v-model:selected-keys="selectedRowKeys" :loading="pageData.pageLoading" :data="table.dataList"
                        :pagination="false"
                        :rowKey="rowKey" :scroll="{ x: '100%', y: '100%', maxHeight: '100%' }">
                        <template #deleteState="{ record }">
                            <a-button v-if="record.deleteState == 1" type="primary" size="small" status="warning"
                                disabled>已删除
                            </a-button>
                        </template>
                        <template #action="{ record }">
                            <a-button type="primary" size="small" status="warning" @click="editHandler(record)"
                                v-if="pageData.isEdit">
                                <template #icon>
                                    <icon-edit />
                                </template>
                                修 改
                            </a-button>
                        </template>
                    </a-table> -->
            <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" :suppressDragLeaveHidesColumns="true" rowSelection="multiple"
                @grid-ready="gridReady" @columnResized="onColumnResized" @columnMoved="onColumnMoved" style="height: calc(100% - 45px);"
                @columnVisible="onColumnVisible" :defaultColDef="defaultColDef" class='ag-theme-alpine'
                :rowData="table.dataList" :columnDefs="tc" :localeText="localeText1"></AgGridVuesCopys>
                <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size
            @change="PageSize" @page-size-change="change1" :page-size="size" :current="page"
            style="justify-content: center" />
        </template>
        
        <a-drawer :style="{ 'zIndex': 999 }" :mask-closable="false" :width="400" :visible="pageData.showAdd"
            :ok-loading="pageData.pageLoading" unmountOnClose @ok="sideOk" @cancel="pageData.showAdd = false"
            cancel-text='关闭' ok-text='保存'>
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-form ref="formRef" layout="horizontal" :model="dataForm">
                    <a-form-item label="织单类型" field="weaveOrderType" :rules="[{ required: true, message: '织单类型必填' }]"
                        :validate-trigger="['change', 'blur']" label-col-flex="100px">
                        <a-input class="bacClass" placeholder="" v-model="dataForm.weaveOrderType" />
                    </a-form-item>
                    <a-form-item label="是否本集团" label-col-flex="100px" field="processType"
                        :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '是否本集团必填' }]">
                        <a-select popup-container="html"  allow-search :class="{ bacClass: true }" v-model="dataForm.processType">
                            <a-option :value="0">本集团</a-option>
                            <a-option :value="1">外加工</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="备注" field="remark" label-col-flex="100px">
                        <!-- <a-input  v-model="dataForm.remark" /> -->
                        <a-textarea class="bacClass" placeholder="" v-model="dataForm.remark" :max-length="400" allow-clear
                            show-word-limit />
                    </a-form-item>

                </a-form>
            </div>
        </a-drawer>

    </pageTabelLayout>
</template>

<script lang="ts">
import { post, get } from "@/api/http";
import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
} from "@/hooks/table";

import { ref, reactive, onMounted } from "vue";
import Toolbar from "@/components/Toolbar.vue";
import { Form, Message, Modal, Pagination } from "@arco-design/web-vue";
import { FormInstance } from "@arco-design/web-vue/es/form";
import emitter from "@/hooks/useEventBus";
import validate from "@/hooks/useValidate";
import { baseURL } from '../../../api/axios.config'
import axios from "axios";
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
interface Cloth {
    merceryCode: string;
}

interface ClothInfo {
    "id": any,
    "weaveOrderType": any,
    "remark": any,
    processType: any
}

export default {
    name: "setingsz",
    setup() {
        const pagingList1: any = ref(pagingList)
        const total = ref(0);
        const page = ref(1);
        const size = ref(10);
        function PageSize(val: any) {
            page.value = val
            doRefresh();
        }
        function change1(val: any) {
            size.value = val
            doRefresh();
        }

        const headerShow = ref<boolean>(true)
        //查询
        const scrollbar = ref(true)

        function doRefresh() {
            pageData.pageLoading = true
            updateGridState01()
            post({
                url: "planSingle/weaveOrderType/getPageInfo",
                data: {
                    page: page.value,
                    size: size.value,
                    deleteState: 0,
                    weaveOrderType: pageData.dropDownData,
                    processType: pageData.outsideState
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        gridOption.value.setRowData(data.list)
                        table.handleSuccess(data.list);
                        total.value = data.total;

                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
        }

        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        //检验表单是否含有中文的方法
        const hasChiese = validate.includeChinese;
        const tableColumns = useTableColumn([
            {
                title: "织单类型",
                key: "weaveOrderType",
                dataIndex: "weaveOrderType",
                slotName: "weaveOrderType",
                width: 150
            },
            {
                title: "是否本集团",
                key: "processType",
                dataIndex: "processType",
                slotName: "processType",
                width: 150
            },
            {
                title: "备注",
                key: "remark",
                dataIndex: "remark",
                width: 150
            },
            {
                title: "创建人",
                key: "createName",
                dataIndex: "createName",
                width: 150
            },

            {
                title: "创建时间",
                key: "createTime",
                dataIndex: "createTime",
                width: 150
            },
            {
                title: "修改人",
                key: "updateName",
                dataIndex: "updateName",
                width: 200
            },
            {
                title: "修改时间",
                key: "updateTime",
                dataIndex: "updateTime",
                width: 150
            },
            {
                title: "操作",
                key: "id",
                dataIndex: "id",
                slotName: "action",
                width: 150, fixed: 'right'
            },
        ]);
        const scroll = {
            x: 2000,
            y: 200
        };
        const tablediv = ref(null)
        const pageData = reactive<{
            clothList: any[]
            showAdd: boolean
            sideTitle: string
            dropDownData: any
            pageLoading: boolean,
            theight: number,
            tablediv: any,
            rHeight: number | undefined,
            btnList: any[],
            isEdit: boolean,
            outsideState: any
        }>({
            clothList: [],
            showAdd: false,
            sideTitle: "新增布料基础资料",
            dropDownData: "",
            pageLoading: false,
            theight: 0,
            tablediv: null,
            rHeight: 0,
            btnList: [],
            isEdit: false,
            outsideState: null
        });
        //下拉框得到焦点
        const focusSel = () => {
            selCxAll({ yarnCode: '', deleteState: 0 })
        }
        //下拉数据
        const options = ref<any>(pageData.clothList);
        const loading = ref(false);
        const handleSearch = (value: any) => {
            if (value) {
                const ob = { yarnCode: value, deleteState: 0 }
                loading.value = true;
                selCxAll(ob);
                options.value = pageData.clothList;
                loading.value = false;
            } else {
                options.value = []
            }
        };
        //下拉框查询
        function selCxAll(val: any) {
            post({
                url: "product/Yarn/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {


                    pageData.clothList = data;

                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }

        onMounted(() => {
            // 切换tap到本页面执行的方法
            // emitter.on("setingsz", () => {
            // selCxAll({});
            doRefresh();
            // });
            pageData.rHeight = document.getElementsByClassName("main-base-style")[0]?.clientHeight
            //表格的高
            if (pageData.rHeight !== undefined) {
                pageData.rHeight = pageData.rHeight - 200;

            }
            window.addEventListener('resize', () => {
                pageData.rHeight = document.getElementsByClassName("main-base-style")[0]?.clientHeight

                //表格的高
                if (pageData.rHeight !== undefined) {
                    pageData.rHeight = pageData.rHeight - 200;
                }

            })

        });
        let cxbl = ""
        //查询
        const selectHandler = () => {
            page.value = 1
            cxbl = pageData.dropDownData
            doRefresh();
        }
        const queryData = reactive({
            clothType: "",
        });
        const addHandler = () => {
            for (var key in dataForm) {
                if (key === "id") {
                    dataForm[key] = null;
                } else {
                    dataForm[key] = "";
                }

            }
            pageData.showAdd = true;
            pageData.sideTitle = "新增织单类型";
        };

        const dataForm = reactive<ClothInfo>({
            id: null,
            "weaveOrderType": "",
            "remark": "",
            processType: null
        });
        const gridOption = ref()
        const colState = ref()
        const gridReady = (params: any) => {
            gridOption.value = params.api
            colState.value = params.columnApi
            //gridOption.value.sizeColumnsToFit();
        }

        const formRef = ref<FormInstance>();
        const sideOk = () => {
            formRef.value?.validate().then((err) => {
                if (!err) {
                    pageData.pageLoading = true;
                    if (pageData.sideTitle === "新增织单类型") {
                        dataForm.id = null
                        post({
                            url: "planSingle/weaveOrderType/insert",
                            data: [dataForm],
                        }).then((res: any) => {
                            if (res.code === 200) {
                                formRef.value?.resetFields();

                                pageData.showAdd = false;

                                Message.success({
                                    content: "新增成功",
                                    duration: 5000,
                                });
                                doRefresh();
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 5000,
                                });
                            }
                        }).finally(() => {
                            pageData.pageLoading = false
                        })
                    } else {
                        post({
                            url: "planSingle/weaveOrderType/update",
                            data: [dataForm],
                        }).then((res: any) => {
                            if (res.code === 200) {
                                formRef.value?.resetFields();
                                pageData.showAdd = false;
                                Message.success({
                                    content: "修改成功",
                                    duration: 5000,
                                });
                                doRefresh();
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 5000,
                                });
                            }
                        }).finally(() => {
                            pageData.pageLoading = false
                        })
                    }
                }
            });
        };
        const deleteHandler = () => {
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选');
                return
            }
            Modal.confirm({
                title: "系统提示",
                content: "确认删除选中的数据?",
                onOk() {
                    pageData.pageLoading = true;
                    post({
                        url: "planSingle/weaveOrderType/deleteZT",
                        data: gridOption.value.getSelectedRows().map((o: any) => { return o.id }),
                    }).then(({ code, message }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: "删除成功",
                                duration: 5000,
                            });

                            pagination.page = 1
                            doRefresh();

                        } else {
                            Message.error({
                                content: message,
                                duration: 5000,
                            });
                        }
                    }).finally(() => {
                        pageData.pageLoading = false
                    });
                },
            });
        };
        const editHandler = (record: ClothInfo) => {
            dataForm.id = record.id;
            dataForm.weaveOrderType = record.weaveOrderType;
            dataForm.remark = record.remark;
            dataForm.processType = record.processType;
            pageData.sideTitle = '修改织单类型'
            pageData.showAdd = true
        };
        //判断是否填写了中文
        const isChiese = (value: string, cb: Function) => {
            return new Promise<void>(resolve => {
                if (window.encodeURI(value).indexOf('%') !== -1) {
                    cb('填写的值只能是英文数字组合或英文，数字！')
                }
                resolve()
            })

        }
        //input离开焦点 将小写转大写
        // const inputBlur = () => {
        //     dataForm.yarnCode = dataForm.yarnCode.toUpperCase();
        // }
        //导出
        const exports = () => {
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选');
                return
            } else {
                let idList: any = []
                gridOption.value.getSelectedRows().forEach(function (o: any) {
                    idList.push(o['id'])
                })
                //将表头拼接出来
                let head = "<th>编号</th><th>名称</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>"
                //拿到当前表格数据与勾选的行做筛选

                let nowRow = table.dataList.filter(function (o) {
                    return (gridOption.value.getSelectedRows().map((o: any) => { return o.id })).indexOf(o["id"]) !== -1;
                })
                let body = "";
                nowRow.forEach(function (o) {
                    body += "<tr><td>" + o["yarnCode"] + "</td>";
                    body += "<td>" + o["yarnName"] + "</td>";
                    body += "<td>" + o["remark"] + "</td>";
                    body += "<td>" + o["createName"] + "</td>";
                    body += "<td>" + o["createTime"] + "</td>";
                    body += "<td>" + o["updateName"] + "</td>";
                    body += "<td>" + o["updateTime"] + "</td>";
                    body += "</tr>";
                })
                tableToXlsx(head, '纱线资料', body)
                console.log(table)
            }
        }

        function tableToXlsx(head: any, filename: any, body: any) {
            const uri = 'data:application/vnd.ms-excel;base64,',
                template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`;

            const a = document.createElement('a');
            a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
            a.download = filename;
            a.click();
            document.removeChild(a);
        }

        //模板下载
        const downloadHandler = () => {
            axios.get(baseURL + '/product/Yarn/uploadModel', {
                responseType: 'blob',
                headers: {
                    token: sessionStorage.getItem('USER-TOKEN-KEY')
                }
            }).then((res) => {
                if (res.status === 200) {
                    filedownload(res.data, '纱线类别.xlsx')
                }
            })
        }
        //导入
        const importHandler = () => {

            const inputEle: HTMLInputElement = document.createElement('input')
            inputEle.type = 'file'
            inputEle.id = 'fileUploadExcel'
            inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
            inputEle.addEventListener('change', (e) => {
                const formData = new FormData()
                if (inputEle.files !== null) {
                    formData.append('file', inputEle.files[0] || '')
                } else {
                    Message.warning('未选择文件！');
                    return
                }
                pageData.pageLoading = true
                axios.post(baseURL + '/product/Yarn/analyseYarnWireModel', formData, {
                    headers: {
                        "Content-Type": 'multipart/form-data',
                        "token": sessionStorage.getItem('USER-TOKEN-KEY')
                    },
                }).then((result) => {
                    if (result.data['code'] === 200) {
                        Message.success('导入成功')
                    } else {
                        Message.error(result.data.message)
                    }

                }).finally(() => {
                    pageData.pageLoading = false
                    doRefresh()
                })
            })
            inputEle.click()
        }
        //设置权限
        // ['查询', '新增', '删除', '导出', '导入']
        const permissionStore = usePermission()

        if (permissionStore.hasPermisson('blzl.cx')) {

            pageData.btnList.push("查询")
        }
        if (permissionStore.hasPermisson('blzl.xz')) {
            pageData.btnList.push("新增")
        }
        if (permissionStore.hasPermisson('blzl.sc')) {
            pageData.btnList.push("删除")
        }
        if (permissionStore.hasPermisson('blzl.dc')) {
            pageData.btnList.push("导出")
        }
        if (permissionStore.hasPermisson('blzl.dr')) {
            pageData.btnList.push("导入")
        }
        if (permissionStore.hasPermisson('blzl.xg')) {
            pageData.isEdit = true
        }
        const handleChange = (_data: any) => {
            table.handleSuccess(_data);
        }
        let tc: any[] = tableColumns.map((o: any) => {

            let obj = {
                headerName: o.title,
                field: o.key,
                pinned: o['fixed']
            }
            obj['width'] = 205
            if (o.slotName === 'action') {
                obj['resizable'] = false
                obj['filter'] = false
                obj['sortable'] = false
                obj["lockPosition"] = "right"
                obj['width'] = 80
                obj['cellRenderer'] = {
                    template: `<a-tag color="#ff7d00" class="gesture" @click="a" v-if="e">修改</a-tag>`,
                    setup(props: any) {
                        const a = () => {
                            editHandler(props.params.data)
                        }
                        return {
                            e: permissionStore.hasPermisson('zdlxwh.xg'),
                            a
                        }
                    }

                }
            }
            if (o.slotName === 'processType') {
                obj['resizable'] = false
                obj['sortable'] = false
                obj['width'] = 200
                obj['cellRenderer'] = {
                    template: `<a-space>
                        <el-tag type="success" @click="a" v-if="a==0">
                            {{val}}
                        </el-tag>
                        <el-tag type="warning"  @click="b" v-if="a==1">
                            {{val}}
                        </el-tag></a-space>`,
                    setup(props: any) {
                        const val = ref()
                        val.value = props.params.data.processType == 0 ? '本集团' : '外加工'
                        return {
                            val,
                            a: props.params.data.processType
                        }
                    },

                }
                obj['filterParams'] = {
                valueFormatter: function (params: any) {
                    return params.value == '0'
                    ? '本集团'
                    : '外加工'
                },
                }
            }

            return obj
        })

        let a = [{
            showRowGroup: 'hide_def',
            "headerName": "",
            "checkboxSelection": true,
            "headerCheckboxSelection": true,
            "pinned": "left",
            "width": 50,
            resizable: false,
            filter: false,
            sortable: false,
            minWidth: 50,
            maxWidth: 50,
            lockPosition: "left",
        }]
        tc = a.concat(tc)
        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
            flex: 1
        }
        const localeText1: any = ref(localeText)
        const huiche = () => {
            doRefresh();
        }
        const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('setingsz-1', gridOption, colState, tc)
        const onColumnMoved = () => {
            saveGridState01()
        }
        const onColumnResized = () => {
            saveGridState01()
        }
        const onColumnVisible = () => {
            saveGridState01()
        }
        return {
            saveOrUpdateGridState01,
            saveGridState01,
            updateGridState01,
            onColumnMoved,
            onColumnResized,
            onColumnVisible,
            colState,
            pagingList1,
            permissionStore,
            huiche,
            localeText1,
            defaultColDef,
            tc,
            total,
            PageSize,
            change1,
            page,
            size,
            scroll,
            scrollbar,
            tablediv,
            downloadHandler,
            importHandler,
            hasChiese,
            deleteHandler,
            sideOk,
            formRef,
            dataForm,
            addHandler,
            selectedRowKeys,
            pagination,
            tableColumns,
            table,
            rowKey,
            pageData,
            queryData,
            editHandler,
            selectHandler,
            options,
            loading,
            handleSearch,
            // inputBlur,
            isChiese,
            exports,
            focusSel,
            headerShow,
            handleChange,
            gridReady
        };
    },
    components: { Toolbar,  },
};
</script>
<style scoped lang="less">
:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}
</style>
